package com.ofek.eventos.net.ocsf.server;



import java.io.IOException;

import com.ofek.eventos.net.ServiceCallBack;
import com.ofek.eventos.net.ocsf.client.Invocation;
import com.ofek.eventos.net.ocsf.client.InvocationResult;

/**
 * 
 * @author Ofek
 *
 */
public class Server extends AbstractServer {
	private final Service service;
	/**
	 * Class constructor
	 * @param port port where server located
	 * @throws IOException 
	 */
	public Server(final int port,final Service service) throws IOException {
		super(port);
		listen();
		this.service = service;
	}


	public void recycle() {
		try {
			close();
		} catch (final IOException e) {
			e.printStackTrace();
		} finally {
			service.close();
		}
	}
	@Override
	protected void handleMessageFromClient(final Object msg, final ConnectionToClient client) {
		final Invocation inv = (Invocation)msg;
		service.handle(inv.r, new ServiceCallBack() {

			@Override
			public void onResult(final Object result) {
				final InvocationResult invocationResult = new InvocationResult(inv.id,true,result);
				try {
					client.sendToClient(invocationResult);
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(final Object error) {
				final InvocationResult invocationResult = new InvocationResult(inv.id,false,error);
				try {
					client.sendToClient(invocationResult);
				} catch (final IOException e) {
					e.printStackTrace();
				}

			}
		});
	}


	//	@Override
	//	protected synchronized void clientDisconnected(ConnectionToClient client) {
	//		connToUserHash.remove(client);
	//	}
	//	@Override
	//	protected synchronized void clientException(ConnectionToClient client,
	//			Throwable exception) {
	//		try {
	//			client.close();
	//		} catch (IOException e) {
	//			// TODO Auto-generated catch block
	//			e.printStackTrace();
	//		}
	//		connToUserHash.remove(client);
	//	}
	//	Timer timer = new Timer();
	//	@Override
	//	protected void clientConnected(final ConnectionToClient client) {
	//		super.clientConnected(client);
	//		timer.scheduleAtFixedRate(new TimerTask() {
	//			
	//			@Override
	//			public void run() {
	//				try {
	//					client.sendToClient(new Mssg(-1));
	//				} catch (IOException e) {
	//					clientDisconnected(client);
	//				}
	//			}
	//		}, 10000,10000);
	//	}

}
